package leecode.二叉树;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author wangxi created on 2020/12/27 10:28
 * @version v1.0
 */
public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }

    public static String serialize(TreeNode root) {
        if (root == null) {
            return "";
        }
        StringBuilder buffer = new StringBuilder();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node != null) {
                    buffer.append(node.val).append(",");
                    queue.offer(node.left);
                    queue.offer(node.right);
                } else {
                    buffer.append("null").append(",");
                }
            }
        }
        return buffer.toString();
    }

    public static TreeNode deserialize(String str) {
        if (str == null || str.length() <= 0) {
            return null;
        }
        String[] parts = str.split(",");
        Queue<TreeNode> queue = new LinkedList<>();
        int rootVal = Integer.parseInt(parts[0]);
        TreeNode root = new TreeNode(rootVal);
        queue.add(root);
        for (int i = 1; i < parts.length; i++) {
            String item = parts[i];
            if (item.length() == 0) {
                continue;
            }
            TreeNode node = queue.poll();
            if (!item.equals("null")) {
                node.left = new TreeNode(Integer.parseInt(item));
                queue.offer(node.left);
            } else {
                node.left = null;
            }
            i++;
            String nextItem = parts[i];
            if (!nextItem.equals("null")) {
                node.right = new TreeNode(Integer.parseInt(nextItem));
                queue.offer(node.right);
            } else {
                node.right = null;
            }
        }
        return root;
    }

    @Override
    public String toString() {
        return val + "";
    }
}
